<template>
  <div class="chat-container">
    <!-- 默认显示 -->
    <div class="logo-push" v-show="messages.length == 0">
      <img src="/logo.png" class="logo" alt="" />
      <div class="push-container">
        <ul class="push-list">
          <li v-for="(message, index) in pushList" @click="handleAuto(message)">
            {{ message.content }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 会话列表 -->
    <div class="chat-messages" ref="chatMessagesRef">
      <div v-for="(item, index) in messages" :key="index" class="message">
        <span
          :class="{
            'user-message': item.role === 'user',
            'system-message': item.role === 'system',
          }"
          v-html="item.content"
        >
        </span>
      </div>
    </div>

    <!-- 提交问题 -->
    <div class="input-container">
      <span class="history" @click="showHistory = true">历史</span>
      <input
        v-model="inputMessage"
        placeholder="输入任何问题"
        @keyup.enter="sendMessage()"
      />
      <button @click="sendMessage()">发送</button>
    </div>

    <!-- 弹窗 -->
    <div class="popup-bg" @click="showHistory = false" v-if="showHistory"></div>
    <div class="popup" v-if="showHistory">
      <span class="close" @click="showHistory = false">关闭</span>
      <h3>推荐问题</h3>
      <ul>
        <template v-for="(item, index) in pushList" :key="index">
          <li v-html="item.content" @click="handleAuto(item)"></li>
        </template>
      </ul>

      <h3>历史问题</h3>
      <ul>
        <template v-for="(item, index) in messages" :key="index">
          <li
            v-html="item.content"
            v-if="item.role == 'user' && item.type == 2"
          ></li>
        </template>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import axios from "axios";
import MarkdownIt from "markdown-it";

const md = new MarkdownIt();

const inputMessage = ref("");
const messages = ref([
  // { role: 'user', content: '你好，AI！' },
  // { role: 'ai', content: '你好！这是一张图片：<img class="chat-image" src="https://picsum.photos/seed/picsum/600/300" alt="example image" />' },
]);

const chatMessagesRef = ref(null);
const showHistory = ref(false);

// 推荐问题
const pushList = ref([
  { content: "父母年迈，我该返乡吗", type: 1 },
  { content: "小花是哪位", type: 1 },
  { content: "“两会”将如何推动AI等新技术发展", type: 1 },
  { content: "如何学会对他人说“不”", type: 1 },
  { content: "两口子总因为家务吵架怎么办", type: 1 },
]);

const handleAuto = (item) => {
  inputMessage.value = item.content;
  showHistory.value = false;
  nextTick(() => {
    sendMessage(item.type);
  });
};

onMounted(async () => {
  // try {
  //   // 发送请求到后端接口
  //   const response = await axios.get('http://localhost:3000/ai-records');
  //   const { code, data, message } = response.data;
  //   if (code === 200) {
  //     // 处理返回的数据
  //     data.forEach(item => {
  //       messages.value.push({
  //         role: "user",
  //         content: item.question,
  //         type: 2,
  //       });
  //       messages.value.push({
  //         role: "system",
  //         content: item.answer,
  //       });
  //     });
  //   }
  // } catch (error) {
  //   console.error("请求出错:", error);
  // }
});

// 发送问题 type: 1推荐问题 2用户问题
const sendMessage = async (type) => {
  if (inputMessage.value.trim() === "") return;

  messages.value.push({
    role: "user",
    content: inputMessage.value,
    type: type == 1 ? 1 : 2,
  });
  inputMessage.value = "";

  nextTick(() => {
    scrollToBottom();
  });

  try {
    // 发送请求到后端接口
    const response = await axios.post('http://localhost:3000/ai-reply', {
      message: messages.value[messages.value.length - 1].content
    });

    // const aiMarkdown =
    //   '你好，**我是AI**。这是一张图片：![示例图片](https://picsum.photos/seed/picsum/800/400 "这是一张示例图片") 请问有什么可以帮助你的吗？';
    // const aiMessage = md.render(aiMarkdown);
    const aiMessage = md.render(response.data.message);

    // 先添加一条空的AI消息记录
    messages.value.push({ role: "system", content: "" });

    let currentIndex = 0;
    let currentText = "";
    const intervalId = setInterval(() => {
      if (currentIndex < aiMessage.length) {
        if (aiMessage[currentIndex] === "<") {
          // 遇到 HTML 标签，直接添加到当前文本
          const endIndex = aiMessage.indexOf(">", currentIndex);
          if (endIndex !== -1) {
            currentText += aiMessage.slice(currentIndex, endIndex + 1);
            currentIndex = endIndex + 1;
          } else {
            // 异常情况，处理不完整标签
            currentText += aiMessage[currentIndex];
            currentIndex++;
          }
        } else {
          // 纯文字，逐个添加
          currentText += aiMessage[currentIndex];
          currentIndex++;
        }

        // 获取最后一条AI消息的索引
        const lastAiMessageIndex = messages.value.length - 1;
        // 更新最后一条AI消息的文本内容
        messages.value[lastAiMessageIndex].content = currentText;
        // 强制更新页面
        messages.value = [...messages.value];

        // 每次更新消息后，在 DOM 更新后滚动到聊天框底部
        nextTick(() => {
          scrollToBottom();
        });
      } else {
        clearInterval(intervalId);
      }
    }, 50);
  } catch (error) {
    console.error("请求出错:", error);
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
  }
};
</script>

<style scoped>
.logo-push {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 60px;
}
.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 40px;
}
.push-container {
  width: 100%;
  overflow: hidden;
  position: relative;
}
.push-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-wrap: wrap;
}
.push-list li {
  margin: 0 10px 10px 0;
  font-size: 14px;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 5px 10px;
  white-space: nowrap;
}

.chat-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
}

.message {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.user-message {
  background-color: #e0f7fa;
  padding: 10px;
  border-radius: 5px;
  align-self: flex-end;
  display: inline-block;
}

.system-message {
  background-color: #f1f8e9;
  padding: 10px;
  border-radius: 5px;
  align-self: flex-start;
  display: inline-block;
}

/* 为消息内的图片添加样式 */
.user-message img.chat-image,
.system-message img.chat-image {
  max-width: 100% !important;
  height: auto !important;
}

.input-container {
  display: flex;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
}

.history {
  padding: 5px 10px;
  background-color: #f5f5f5;
  border-radius: 5px;
  margin-right: 10px;
}

input {
  flex: 1;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

button {
  padding: 5px 20px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.popup-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}
.popup {
  position: fixed;
  width: 70vw;
  height: 100vh;
  top: 0;
  left: 0;
  background-color: white;
  padding: 15px;
  z-index: 1000;
}

.popup .close {
  position: absolute;
  top: 15px;
  right: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 28px;
  font-size: 14px;
  padding: 0 10px;
}
.popup ul {
  list-style-type: none;
  padding: 0;
  margin-top: 10px;
}
.popup li {
  margin-bottom: 5px;
  font-size: 14px;
  color: #666;
  background-color: #fff;
  border-radius: 4px;
  padding: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}
.popup li:hover,
.popup li:active {
  background-color: #f5f5f5;
}
</style>
